package com.zhkj.txg.module.home.ui

import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.view.View
import android.view.ViewTreeObserver
import android.widget.ImageView
import android.widget.TextView
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.zhkj.lib.base.ViewModelActivity
import com.zhkj.lib.http.HttpResponseStatus
import com.zhkj.lib.utils.AccountManager
import com.zhkj.lib.utils.ScreenUtil
import com.zhkj.txg.R
import com.zhkj.txg.module.home.adapter.HomeBannerAdapter
import com.zhkj.txg.module.home.adapter.HomeCateAdapter
import com.zhkj.txg.module.home.adapter.MallAdapter
import com.zhkj.txg.module.home.adapter.MallProductAdapter
import com.zhkj.txg.module.home.entity.BannerEntity
import com.zhkj.txg.module.home.vm.MallViewModel
import com.zhkj.txg.utils.ImageUtils
import com.zhkj.txg.utils.typeJump
import com.youth.banner.Banner
import kotlinx.android.synthetic.main.activity_mall.*
import kotlin.math.abs

class MallActivity : ViewModelActivity<MallViewModel>() {

    companion object {
        fun open(activity: Activity) {
            activity.startActivity(Intent(activity, MallActivity::class.java))
        }
    }

    override fun setViewModel(): MallViewModel = createViewModel()
    override fun statusTitleBar(): View? = topViewMall
    override val layoutResId: Int = R.layout.activity_mall

    private lateinit var banner: Banner<BannerEntity, HomeBannerAdapter>
    private lateinit var shopTop: View
    private lateinit var tvMallEnterShop: View
    private lateinit var tvMallShopName: TextView
    private lateinit var ivMallShop: ImageView
    private var maxScrollHeight = 0
    private val mallAdapter = MallAdapter().apply {
        headerWithEmptyEnable = true
        loadMoreModule?.isEnableLoadMore = true
        loadMoreModule?.setOnLoadMoreListener {
            viewModel.mallShopList(AccountManager.getToken())
        }
    }
    private val mallCateAdapter = HomeCateAdapter().apply {
        setOnItemClickListener { _, _, position ->
            val entity = data[position]
            MallCategoryActivity.open(this@MallActivity, entity.name, entity.id)
        }
    }
    private val productAdapter = MallProductAdapter()

    override fun initViewModel() {
        // 店铺数据观察者
        viewModel.mallShopLiveData.observe(this, Observer { response ->
            when (response.status) {
                HttpResponseStatus.Status.START -> Unit
                HttpResponseStatus.Status.SUCCESS -> response.response?.let {
                    // 判断加载状态
                    if (!it.loadMore) refreshMall.finishRefresh()
                    else if (it.hasMore) mallAdapter.loadMoreModule?.loadMoreComplete()
                    else mallAdapter.loadMoreModule?.loadMoreEnd()
                    // 数据填充
                    if (it.loadMore) mallAdapter.addData(it.data)
                    else mallAdapter.setNewData(it.data)
                }
                HttpResponseStatus.Status.FAILURE -> {
                    response.exception?.printStackTrace()
                    toast(response.statusTip)
                    if (viewModel.page > 1) mallAdapter.loadMoreModule?.loadMoreFail()
                    else refreshMall.finishRefresh(false)
                }
            }
        })
        // 首页数据观察者
        viewModel.mallLiveData.observe(this, Observer { response ->
            handlerResponseStatus(response.status, response.statusTip)
            if (response.status == HttpResponseStatus.Status.SUCCESS) response.response?.data?.let { data ->
                // 设置Banner
                banner.setDatas(data.banner).start()
                // 设置分类数据
                mallCateAdapter.setNewData(data.category)
                // 设置店铺
                if (data.topShop != null) {
                    shopTop.visibility = View.VISIBLE
                    tvMallShopName.text = data.topShop.shopName
                    tvMallEnterShop.setOnClickListener {
                        ShopActivity.open(this, data.topShop.shopName, data.topShop.id)
                    }
                    ImageUtils.loadCircleImage(this@MallActivity, ivMallShop, data.topShop.shopImg)
                    productAdapter.setNewData(data.topShop.goods)
                } else shopTop.visibility = View.GONE
            }
        })
    }

    override fun initUI() {
        // 获取变色的最大滚动距离
        topViewMall.viewTreeObserver.addOnGlobalLayoutListener(object :
            ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                maxScrollHeight =
                    (ScreenUtil.getScreenWidth(this@MallActivity) * 0.75 - topViewMall.measuredHeight).toInt()
                topViewMall.viewTreeObserver.removeOnGlobalLayoutListener(this)
            }
        })
        with(rvMall) {
            layoutManager = LinearLayoutManager(this@MallActivity)
            adapter = mallAdapter
            addOnScrollListener(object : RecyclerView.OnScrollListener() {
                val llm = layoutManager as LinearLayoutManager
                val pos = IntArray(2)
                override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                    // 设置title的透明度
                    if (llm.findFirstVisibleItemPosition() == 0 && llm.getChildAt(0) != null) {
                        llm.getChildAt(0)!!.getLocationInWindow(pos)
                        if (abs(pos[1]) <= maxScrollHeight) {
                            val alpha = (abs(pos[1]).toFloat() / maxScrollHeight * 255).toInt()
                            topViewMall.setBackgroundColor(Color.argb(alpha, 255, 255, 255))
                            titleMall.setLeftIcon(R.drawable.ic_back).setDividerVisible(false)
                            tvMallSearch.setBackgroundResource(R.drawable.bg_round_white_30dp_transparent)
                        } else {
                            topViewMall.setBackgroundColor(Color.argb(255, 255, 255, 255))
                            titleMall.setDividerVisible(true).setLeftIcon(R.drawable.ic_arrow_left_black)
                            tvMallSearch.setBackgroundResource(R.drawable.bg_round_gray_100)
                        }
                    }
                }
            })
        }
        with(mallAdapter) {
            setEmptyView(R.layout.layout_empty_data)
            setHeaderView(createHeaderView())
        }
        // 打开搜索页面
        tvMallSearch.setOnClickListener {
            SearchActivity.homeOpen(this, 0)
        }
        // 打开购物车
        ivBasket.setOnClickListener {
            startActivity(Intent(this, CartActivity::class.java))
        }
        refreshMall.setOnRefreshListener { initData() }
    }

    override fun initData() {
        viewModel.mallData(AccountManager.getToken(), true)
    }

    /**
     * 生成顶部视图
     */
    private fun createHeaderView(): View =
        layoutInflater.inflate(R.layout.item_mall_header, null).apply {
            banner = findViewById(R.id.bannerMall)
            tvMallShopName = findViewById(R.id.tvMallShopName)
            ivMallShop = findViewById(R.id.ivMallShop)
            tvMallEnterShop = findViewById(R.id.tvMallEnterShop)
            with(findViewById<RecyclerView>(R.id.rvMallCate)) {
                isNestedScrollingEnabled = false
                layoutManager = GridLayoutManager(this@MallActivity, 5)
                adapter = mallCateAdapter
            }
            with(findViewById<RecyclerView>(R.id.rvMall)) {
                hasFixedSize()
                layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
                adapter = productAdapter
            }
            shopTop = findViewById(R.id.shopMallTop)
            // 配置banner
            banner.addBannerLifecycleObserver(this@MallActivity).setAdapter(HomeBannerAdapter(context))
                .setOnBannerListener { data, _ ->
                    (data as? BannerEntity)?.let {
                        typeJump(this@MallActivity, it.jumpType ?: 0, it.params, it.title)
                    }
                }
        }
}